<template>
  <div class="card">
    <div v-if="data.user.role === 'USER'" style="padding:20px; font-size: large ;font-weight: bolder;">我的评论</div>
    <div v-else="data.user.role === 'ADMIN'" style="padding:20px; font-size: large ;font-weight: bolder;">用户评论</div>
    <el-table class="card" :data="data.tableData" border style="width: 100%"
              :header-cell-style="{ color:'#333', backgroundColor:'#fff',}" >
      <el-table-column type="index" label="索引" width="60px" />
      <el-table-column prop="userName" label="评论人昵称"  />
      <el-table-column prop="content" label="评论内容"  />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20]"
          :total="data.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import request from "@/utils/request.js";
import {reactive} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: null,
  totalData:[]
})

const loadComments = () => {
    request.get("/comment/selectPage", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
      }
    }).then(res => {
      if (res.code === '200') {
        console.log(res.data)
        data.tableData = res.data?.list;
        data.total = res.data?.total;
      }else
        ElMessage(res.msg);
    })
}
loadComments()

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认吗？', '删除确认窗口', {type: 'warning',})
    .then(res => {
      request.delete(`/comment/delete/${id}`).then((res) => {
        if (res.code === '200') {
          ElMessage.success('删除成功');
          loadComments()
        } else {
          ElMessage.error(res.msg);
        }
      })
    }).catch(err => {})
}

const handlePageChange = (newPageNum) => {
  data.pageNum = newPageNum;
  loadComments(); // 重新加载数据
};

const handleSizeChange = (newPageSize) => {
  data.pageSize = newPageSize;
  data.pageNum = 1; // 重置为第一页
  loadComments();
};

</script>

<style scoped>

</style>